package cn.fbs.passcontroller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.springframework.web.bind.annotation.GetMapping;

import java.text.DecimalFormat;
import java.util.ArrayList;

public class ServerController {

    @ApiOperation("查询服务器信息")
    @GetMapping("users/getServerInfo")
    public Object getServerInfo() throws SigarException {
        Sigar sigar = new Sigar();
        JSONObject jsonObject = new JSONObject();
        JSONObject memoryInfo = new JSONObject();
        Mem mem = sigar.getMem();
        Double total = (double) mem.getTotal() / (1024 * 1000 * 1000);
        DecimalFormat df = new DecimalFormat("#.00");
        Double used = (double)mem.getActualUsed() / (1024L * 1000 * 1000);
        Double free = (double) mem.getActualFree() / (1024L * 1000 * 1000);
        memoryInfo.put("memoryTotal","内存总量:    " +df.format(total)  + "GB");
        memoryInfo.put("memoryFree","内存可用量:    " +df.format(free)  + "GB");
        memoryInfo.put("memoryUsed","内存使用量:    " +df.format(used)  + "GB");
        memoryInfo.put("memoryPerUsed","内存可用量百分比:    " +df.format(100*(free/total))+"%");
        memoryInfo.put("memoryPerFree","内存使用量百分比:    " +df.format(100*(used/total))+"%");
        CpuPerc[] cpuPercList = sigar.getCpuPercList();
        ArrayList<JSONObject> list = new ArrayList();
        for (int i = 0; i < cpuPercList.length; i++) {
            JSONObject cpuInfo = new JSONObject();
            cpuInfo.put("number","CPU" + (i + 1)+" " );
            String format = CpuPerc.format(cpuPercList[i].getCombined());
            cpuInfo.put("used",format);
            list.add(cpuInfo);
        }
        JSONObject serverInfo = new JSONObject();
        serverInfo.put("serverStatus","服务运行正常");
        jsonObject.put("memoryInfo",memoryInfo);
        jsonObject.put("cpuList",list);
        jsonObject.put("serverInfo",serverInfo);
        return jsonObject;
    }
}
